//
//  ServerViewController.m
//  YYZB
//
//  Created by BY_R on 16/4/7.
//
//

#import "ServerViewController.h"
#import "WebViewManager.h"
#import "WXApiRequestHandler.h"
#import "WXApiManager.h"
#import "MainViewController.h"

#import "AppConfiguration.h"
#import "AppDelegate.h"

#import "WXApiRequestHandler.h"
#import "WXApiManager.h"

static NSString * webViewMessageNameStartWeChatFriend = @"startWeChatFriend";
static NSString * webViewMessageNameStartWeChatTimeline = @"startWeChatTimeline";
static NSString * webViewMessageNameGotoMyInfos = @"gotoMyInfos";

static NSString * webViewMessageNameStartWeChatPayment = @"startWeChatPayment";
static NSString * webViewMessageNameGotoMyOrders = @"gotoMyOrders";

@interface ServerViewController ()

@end

@implementation ServerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameStartWeChatFriend];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameStartWeChatTimeline];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameGotoMyInfos];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameStartWeChatPayment];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:webViewMessageNameGotoMyOrders];
}

- (void)viewDidAppear:(BOOL)animated {
    
    if (self.keepState) {
        return;
    }
    
    [super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    if (self.presentedViewController) {
        self.keepState = YES;
    } else {
        self.keepState = NO;
    }
}

- (NSString *)baseURL {
    return @"http://yyzbhs.einwin.com/pages/";
//    return @"http://testyyzbhs.einwin.com/pages/";
    
    
    
//    return [AppConfiguration isProductionEnv] ? @"http://yyzbhs.einwin.com/pages/" : @"http://xtyyzb.einwin.com:83/pages/";
//    return @"http://115.29.179.142:4004/YYZB/HTML_SERVICE/pages/";
//    return @"http://xtyyzb.einwin.com:83/pages/";
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    [super userContentController:userContentController didReceiveScriptMessage:message];
    /*
     
     {
     
     "shareid": "分享ID",
     
     "title": "标题",
     
     "desc": "描述",
     
     "url": "链接",
     
     
     }
     
     */
    
    //微信好友
    if ([message.name isEqualToString:webViewMessageNameStartWeChatFriend]) {
        id body = message.body;
        NSDictionary *bd;
        if ([body isKindOfClass:[NSDictionary class]]) {
            bd = body;
        } else if ([body isKindOfClass:[NSString class]]) {
            bd = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
            
        }
        bd = [NSDictionaryNullKiller dataByReplacingNullWithEmptyString:bd];
        [UserInfoController setWeChatShareID:bd[@"shareid"] ?: @""];
        BOOL b = [WXApiRequestHandler sendLinkURL:bd[@"url"] TagName:nil Title:bd[@"title"] Description:bd[@"desc"] ThumbImage:[UIImage imageNamed:@"icon"] InScene:WXSceneSession];
        NSLog(@"%@", @(b));
        if (!b) {
            UIAlertView *a = [[UIAlertView alloc] initWithTitle:nil message:@"未安装微信" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [a show];
        }
    }
    //朋友圈
    else if ([message.name isEqualToString:webViewMessageNameStartWeChatTimeline]) {
        id body = message.body;
        NSDictionary *bd;
        if ([body isKindOfClass:[NSDictionary class]]) {
            bd = body;
        } else if ([body isKindOfClass:[NSString class]]) {
            bd = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
            
        }
        bd = [NSDictionaryNullKiller dataByReplacingNullWithEmptyString:bd];
        [UserInfoController setWeChatShareID:bd[@"shareid"] ?: @""];
        BOOL b = [WXApiRequestHandler sendLinkURL:bd[@"url"] TagName:nil Title:bd[@"title"] Description:bd[@"desc"] ThumbImage:[UIImage imageNamed:@"icon"] InScene:WXSceneTimeline];
        NSLog(@"%@", @(b));
        if (!b) {
            UIAlertView *a = [[UIAlertView alloc] initWithTitle:nil message:@"未安装微信" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [a show];
        }
    }
    else if ([message.name isEqualToString:webViewMessageNameGotoMyInfos]) {
        UIStoryboard * story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        MainViewController * vc = [story instantiateViewControllerWithIdentifier:@"MainViewController"];
        vc.selectedIndex = 2;
        vc.delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [UIApplication sharedApplication].keyWindow.rootViewController = vc;
    }
    else if ([message.name isEqualToString:webViewMessageNameStartWeChatPayment]) {
        id body = message.body;
        NSDictionary *bd;
        if ([body isKindOfClass:[NSDictionary class]]) {
            bd = body;
        } else if ([body isKindOfClass:[NSString class]]) {
            bd = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
        }
        bd = [NSDictionaryNullKiller dataByReplacingNullWithEmptyString:bd];
        [self bizPay:bd];
    }
    else if ([message.name isEqualToString:webViewMessageNameGotoMyOrders]) {
        if (self.navigationController.viewControllers[1]) {
            [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
        } else {
            [self.navigationController popToRootViewControllerAnimated:NO];
        }
    }
}

- (void)bizPay:(NSDictionary *)bd {
    NSString *res = [WXApiRequestHandler jumpToBizPay:bd];
    if( ![@"" isEqual:res] ){
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"支付失败" message:res delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [alter show];
    }
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
